package com.atguigu.spzx.product.service.Impl;

import com.atguigu.spzx.model.entity.product.Category;
import com.atguigu.spzx.product.mapper.CategoryMapper;
import com.atguigu.spzx.product.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author syh
 * @create 2023-08-30 13:02
 */
@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    @Cacheable(value = "index:cates",key = "'one'")
    public List<Category> findOneCategory() {
        return categoryMapper.findOneCategory();
    }

    @Override
    @Cacheable(value = "index:cates",key = "'all'")
    public List<Category> findCategoryTree() {
        //查询所有的分类
        List<Category> categories = categoryMapper.findAllCategories();
        //-- 如果sql中实现父子数据查询绑定：sql需要多表联查、自定义解析查询结果集
        //业务将查询到的分类组装成父子嵌套集合
        //1、挑选出1级分类
        List<Category> oneCategoryList = categories.stream().filter(category -> category.getParentId().longValue() == 0)
                .collect(Collectors.toList());
        //2、为每个一级分类查询并设置它的下一级分类
        oneCategoryList.forEach(oneCategory->{
            //二级分类
            List<Category> twoCategoryList = categories.stream().filter(category ->
                            // 使用正在遍历的一级分类的id和 其他分类的parentid比较
                            category.getParentId().longValue() == oneCategory.getId().longValue())
                    .collect(Collectors.toList());
            oneCategory.setChildren(twoCategoryList);//设置子分类集合
            oneCategory.setHasChildren(!CollectionUtils.isEmpty(twoCategoryList));
            //给二级分类设置三级分类：
            twoCategoryList.forEach(twoCategory->{

                List<Category> threeCategoryList = categories.stream().filter(category ->
                                twoCategory.getId().longValue() == category.getParentId().longValue())
                        .collect(Collectors.toList());
                twoCategory.setChildren(threeCategoryList);
                twoCategory.setHasChildren(!CollectionUtils.isEmpty(threeCategoryList));

            });

        });
        return oneCategoryList;
    }
}
